#include <rtthread.h>
#include <rtdevice.h>
#include "rtdef.h"
#include "rttypes.h"
#include "referee.h"
#include "robotdef.h"

#define THREAD_PRIORITY         25
#define THREAD_TIMESLICE        10

#define LOG_TAG              "REFEREE"
#define LOG_LVL              LOG_LVL_DBG
#include <ulog.h>

#define REFEREE_UART_NAME       "uart6"      /* 串口设备名称 */

/* 串口设备句柄 */
static rt_device_t referee_serial;
/* 初始化配置参数 */
struct serial_configure referee_config = RT_SERIAL_CONFIG_DEFAULT;  
/* 指向信号量的指针 */
static rt_sem_t referee_sem = RT_NULL;

static rt_uint8_t buffer[255];


/* 接收数据回调函数 */
static rt_err_t referee_recv(rt_device_t dev, rt_size_t size)
{
    rt_device_read(dev, -1, &buffer, size);

    rt_sem_release(referee_sem);
    return RT_EOK;
}

static void referee_thread_entry(void *parameter)
{
    rt_err_t result;

    while (1)
    {
        result = rt_sem_take(referee_sem,RT_WAITING_FOREVER);
        if (result==RT_EOK)
        {
            JudgeReadData(buffer);
        }
        rt_thread_mdelay(2);
    }
}



int referee_init(void)
{
    rt_err_t ret = RT_EOK;

    /* 查找串口设备 */
    referee_serial = rt_device_find(REFEREE_UART_NAME);
    if (!referee_serial)
    {
        LOG_E("find %s failed!\n", REFEREE_UART_NAME);
        return RT_ERROR;
    }

    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    rt_device_control(referee_serial, RT_DEVICE_CTRL_CONFIG, &referee_config);

    /* 以 DMA 接收及轮询发送方式打开串口设备 */
    rt_device_open(referee_serial, RT_DEVICE_FLAG_RDWR |RT_DEVICE_FLAG_RX_NON_BLOCKING | RT_DEVICE_FLAG_TX_BLOCKING);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(referee_serial, referee_recv);

    /* 创建一个动态信号量，初始值是 0 */
    referee_sem = rt_sem_create("referee_sem", 0, RT_IPC_FLAG_PRIO);
    if (referee_sem == RT_NULL)
    {
        LOG_E("create dynamic semaphore failed.\n");
        return -1;
    }

    /* 创建 serial 线程 */
    rt_thread_t thread = rt_thread_create("referee", referee_thread_entry, RT_NULL, 2048, 20, 10);
    /* 创建成功则启动线程 */
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    else
    {
        ret = RT_ERROR;
    }

    LOG_D("referee thread init success!\n");

    return ret;
}

#if defined (SENTRY_BOARD_CHASSIS)
   INIT_APP_EXPORT(referee_init);
#endif 

